package com.gupao.javavip.netty.push.client.processor.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.apachecommons.CommonsLog;

@CommonsLog
public abstract class AbstractPushMsgClientHandler<T> extends SimpleChannelInboundHandler<T> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("与客户端断开连接:" + cause.getMessage(), cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, T response) throws Exception {
        String tips = buildReadTips();
        log.info(tips + "：" + response.toString());

        if (checkResponseCode(response)) {
            whenResponseCodeIsSuccess(response);
        } else {
            whenResponseCodeIsFailure(response);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与服务器端断开连接...");
        super.channelInactive(ctx);
    }

    protected boolean checkResponseCode(T response) {
        return true;
    }

    protected void whenResponseCodeIsSuccess(T response) {
    }

    protected void whenResponseCodeIsFailure(T response) {
    }

    protected abstract String buildReadTips();
}
